<template>
	<view>
		<view class="u-page">
			<view v-if="!mapper">
				<view class="item" v-for="(item, index) in list" :key="index" @click="showDetail(item)" >
					<view class="title">
						{{item.name}} ({{item.phone}})
					</view>
					<view class="tab">{{item.yqCity}}</view>
					<view class="lens">
						<view class="key">身份证:</view>
						<view class="value">{{item.credentialsNo}}</view>
					</view>
					<view class="lens">
						<view class="key">目的地:</view>
						<view class="value">{{item.mdd}}</view>
					</view>
					<view class="lens">
						<view class="key">申报时间:</view>
						<view class="value">{{item.createTime}}</view>
					</view>
				</view>
			</view>
			<view v-else class="mapperlist">
				
				<u-sticky bgColor="#fff" zIndex="1">
					<view class="statustab" v-if="status">
						<u-tabs :list="status" @click="changeStatusIndex" :current="statusIndex"></u-tabs>
					</view>

					<view class="filterObject" v-if="filterObject && filterObject.type == 'component'">
						<huocheType v-if="filterObject.name == 'huocheType'" mode="search" @confirm="carTpyeChange"></huocheType>
					</view>
					<view class="filterObject" v-if="filterObject && filterObject.type == 'form'" >
						<u-cell-group>
							<view v-for="(item, index) in filterObject.items" :key="index">
								<u-cell :title="item.label" :value="item.value || item.placeholder" :isLink="true" @click="doTreePicker(item)" v-if="item.type == 'tree-picker'"></u-cell>
								<view style="padding: 10rpx 20rpx;" v-else-if="item.type == 'text'"><u-search :placeholder="item.placeholder" :clearabled="true" :showAction="false" v-model="item.value" @search="onFilterSearch(item)"></u-search></view>
							</view>
						</u-cell-group>
					</view>


				</u-sticky>
	
				<view class="item" v-for="(item, index) in list" :key="index" :class="item.itemClz" @click.prevent="showDetailCommon(item)">
					
					<view class="title" v-if="item.__title || item.__subTags || item.__status">
						{{item.__title}}
						<view class="subTags" v-if="item.__subTags">
							<view class="item" v-for="(s, si) in item.__subTags" :key="si">{{s}}</view>
						</view>
						<view class="status" v-if="item.__status">
							<u-tag :text="item.__status" :type="item.__statusClz" plain plainFill></u-tag>
						</view>
					</view>
					<view class="extTags" v-if="item.__extTags">
						<view class="item" v-for="(s, si) in item.__extTags" :key="si">{{s}}</view>
					</view>
					<view class="lens" v-for="(len, lenIndex) in mapper.list" :key="lenIndex">
						<view class="key">{{len.label}}</view>
						<view class="value">{{item[len.prop]}}</view>
					</view>
					<u-parse v-if="item.__templateHtml" :content="item.__templateHtml"/>
					<view v-if="item.__templateHtml" v-html="item.__templateHtml"></view>
					<view class="buttons" v-if="item.__buttons && item.__buttons.length">
						<view class="button" v-for="(obj,j) in item.__buttons" :key="j">
							<u-button :style="obj.style" :type="obj.type" v-if="obj.show"
						 	 :plain="true" size="small" @click.native.stop.prevent="handleExtButtonClick(obj, item)">{{obj.label}}</u-button>
						</view>
						
					</view>
					<view class="footer" v-if="item.__footer" v-show="item.__footer.show" :style="item.__footer.style">
						<view :style="obj.style" v-for="(obj,j) in item.__footer.items" :key="j" v-show="obj.show"
							@click.native.stop.prevent="handleExtButtonClick(obj, item)" >
							{{obj.label}}
						</view>
						
					</view>
				</view>
                <u-loadmore :status="loadStatus" v-if="startSearch"/>
				<u-empty mode="search" v-if="isEmpty"></u-empty>
				<u-empty mode="permission" v-if="errorMsg" :text="errorMsg"></u-empty>
			</view>

			<view class="emptyBlock" v-if="buttonBtns && buttonBtns.paddingTopStyle">
				<view class="emptyBlock" :style="buttonBtns.paddingTopStyle"></view>
			</view>
			<view class="viewBottomBtn" v-if="buttonBtns && buttonBtns.btns" v-show="buttonBtns.btns.length" :style="buttonBtns.style">
				<view class="btn" v-for="(btn, btnIndex) in buttonBtns.btns" :key="btnIndex" :style="btn.style">
					<u-button :type="btn.type" :text="btn.text" @click="buttonBtnsClick(btn)"></u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import sceneMixins from '@/utils/sceneMixins';
	import huocheType from '@/components/huocheType/index.vue';
	export default {
		mixins: [sceneMixins],
		components: {
			huocheType
		},
		data() {
			return {
				list: [],
				status: '',
				mapper: '',
				statusIndex: 0,
				isEmpty: false,
                errorMsg: '',
                loadStatus: 'loadmore',
                page: 1,
				filterObject: '',
				buttonBtns: '',
				startSearch: false
			}
		},
		onLoad(options) {
			var vm = this;
			if (options.pick) {
				vm.pick = options.pick;
			}
			if (options.query) {
				var queryObj = JSON.parse(decodeURIComponent(options.query));
				Object.assign(options, queryObj);
				vm.initPage(options);
			} else if (options.loadJSON) {
				vm.getAndLoad('获取列表配置', options.loadJSON, (res) => {
					Object.assign(res, options);
					vm.initPage(res);
				});
			} else {
				vm.initPage(options);
			}
		},
        onReachBottom() {
            if (this.loadStatus != 'nomore') {
                this.page = ++this.page;
                this.getList();
            }
        },
		onShow: function () {
			if (global.listPageNeedReload) {
				this.page = 1;
				this.getList();
				global.listPageNeedReload = false;
			}
			let pages = getCurrentPages();
			let currPage = pages[ pages.length - 1];
            // #ifdef MP-WEIXIN
            if(currPage.data.callBackData){
            	this.treePickerConfirm(currPage.data.callBackData);
            }
            currPage.data.callBackData = undefined;
            // #endif

		},
		methods: {
			carTpyeChange: function (obj) {
				var values = obj.split(':');
				var queryObj = {
					carTypeName: values[0].replace('全部', ''),
					carSecondTypeName: values[1].replace('全部', ''),
					carThirdTypeName: values[2]
				};
				this.statusQueryString = this.$Util.stringify(queryObj);
				this.page = 1;
				this.getList();
			},
			buttonBtnsClick: function (btn) {
				var vm = this;
				vm.throttle(500);
				if (btn.validateBefore) {
					var value = this.getFmtStr(btn.validateBefore[0], {});
					var validate = btn.validateBefore[1] ? btn.validateBefore[1].include(value) : value;
					if (!validate) {
						uni.$u.toast(btn.denyTip);
						return;
					}
				}
				if (btn.url) {
					uni.navigateTo({url: this.getFmtStr(btn.url, {})})
				}
			},
			doTreePicker: function (item) {
				this.currentFormField = item;
				uni.setStorageSync('currentPicked', item.value || []);
				if (item.pickerPage) {
					uni.navigateTo({ url: item.pickerPage });
				} else {
                    var params = {
                        autoSearch: item.autoSearch,
                        title: item.placeholder,
                        loadApi: encodeURIComponent(this.getFmtStr(item.optionApi)),
                        ...(item.pickerExtOptions || {})
                    };
					// 打开之前把这两个清掉，不然会显示之前的信息 
					uni.setStorageSync('pickerOptions', []);
					uni.setStorageSync('currentPicked', item.value || []);
					uni.navigateTo({ url: '/pages/tree/index?' + this.$Util.stringify2(params) });
				}
			},
			onFilterSearch: function (item) {
				this.filterObject.queryObj[item.prop] = item.value;
				this.statusQueryString = this.$Util.stringify(this.filterObject.queryObj);
				this.page = 1;
				this.getList();
			},
			treePickerConfirm: function (data) {
				var d = data[0];
				this.currentFormField.value = d.name;

                if (this.filterObject.bindIdMap || this.filterObject.queryObj) {
                    if (this.filterObject.bindIdMap) {
                    	var keys = Object.keys(this.filterObject.bindIdMap);
                    	keys.forEach(key => {
                    		if (d[key] != undefined) {
                    			this.filterObject.queryObj[this.filterObject.bindIdMap[key]] = d[key];
                    		}
                    	});
                    } else if (this.filterObject.queryObj) {
                    	var keys = Object.keys(this.filterObject.queryObj);
                    	keys.forEach(key => {
                    		if (d[key] != undefined) {
                    			this.filterObject.queryObj[key] = d[key];
                    		}
                    	});
                    }
                    this.statusQueryString = this.$Util.stringify(this.filterObject.queryObj);
                    this.page = 1;
                    this.getList();
                }
				
			},
			initPage: function (options) {
				var vm = this;
				if (options.title) {
					uni.setNavigationBarTitle({
						title: options.title
					});
				}
				var listApi = '/mobile/h5/covid19/apiZzsb/getList.jsp?openId=【openId】';
				
				if (options.listApi) {
					listApi = options.listApi;
				}

				if (options.detailPage) {
					vm.detailPage = options.detailPage;
					if (!vm.detailPage.title) {
						vm.detailPage.title = options.title || '信息详情';
					}
				}
				vm.listApi = listApi;
				if (options.status) {
					var status = options.status.split('$').map((m, i) => {
						return {
							name: m.split(':')[1],
							active: !i,
							value: m.split(':')[0],
						};
					});
					vm.status = status;
				}
				if (options.filterObject) {
					vm.filterObject = options.filterObject;
					vm.$nextTick(() => {
						if (vm.filterObject.stopAutoSearch && vm.filterObject.type == 'form') {
							vm.filterObject.items.forEach(n => {
								if (n.type == 'tree-picker') {
									if (n.autoSelect) {
										vm.getAndLoad('提前搜索列表', vm.getFmtStr(n.optionApi), function (res) {
											n.options = res.data;
											if (res.data.length) {
												vm.currentFormField = n;
												vm.treePickerConfirm([res.data[0]])
											}
										})
									} else if (n.autoOpen) {
										vm.doTreePicker(n);
									}
								}
							})
						}
					});

				}

				if (options.mapper) {
					vm.mapper = options.mapper;
				}

				if (options.buttonBtns) {
					vm.buttonBtns = options.buttonBtns;
				}

				vm.doWxLogin().then(res => {
					vm.openId = res.openId;
					vm.getList();			
				});
			},
			getList() {
				var vm = this;
                vm.loadStatus = 'loading';
				var listApi = vm.listApi;
				// listApi = listApi.replace('【openId】', vm.openId);
				listApi = vm.getFmtStr(listApi, {});
				if (vm.status) {
					var activeStatus = vm.status.find(n => n.active).value;
					listApi += ('&status=' + activeStatus);
				}
				if (vm.filterObject && vm.filterObject.stopAutoSearch && !vm.statusQueryString) {
					return;
				}
				if (vm.statusQueryString) {
					listApi += ('&' + vm.statusQueryString);
				}
                
                var paginationParams = '&pageSize=20&page=' + vm.page;
                if (vm.page == 1) {
                    vm.list = [];
                    uni.showLoading({
                    	title: '正在获取信息'
                    })
                }
				
				vm.isEmpty = false;
                vm.errorMsg = '';
				vm.startSearch = true;
				vm.getAndLoad('获取列表', listApi + paginationParams, function (res2) {
					uni.hideLoading();
                    if (res2.code != 0) {
                        vm.errorMsg = res2.msg || '加载失败';
						vm.startSearch = false;
                        return;
                    }
                    if (res2.data.length < 20) {
                        vm.loadStatus = 'nomore';
                    } else {
                        vm.loadStatus = 'loadmore';
                    }
					if (vm.mapper) {
						vm.list = vm.list.concat(res2.data.map(n => {
							var newObj = { ...n };
							newObj.__title = vm.getFmtStr(vm.mapper.title, n);
							// 状态
							// debugger
							if (vm.mapper.subTags) {
								newObj.__subTags = vm.getFmtStr(vm.mapper.subTags, n).split(',').filter(n => n);
							}
							if (vm.mapper.extTags) {
								newObj.__extTags = vm.getFmtStr(vm.mapper.extTags, n).split(',').filter(n => n);
							}
							if (vm.mapper.statusId) {
								var __status = n[vm.mapper.statusId];
								newObj.__status = __status;
								
								if (vm.mapper.statusStyleMap) {
									newObj.__statusClz = vm.mapper.statusStyleMap[__status];
								}
								if (!newObj.__statusClz) {
									if (__status.includes('不通过') || __status.includes('未通过')) {
										newObj.__statusClz = 'error';
									} else if (__status.includes('待') || __status.includes('未')) {
										newObj.__statusClz = 'warning';
									} else if (__status.includes('通过')) {
										newObj.__statusClz = 'success';
									} else {
										newObj.__statusClz = 'info';
									}
								}
							}
							if (vm.mapper.itemClzMapper) {
								var __status = n[vm.mapper.statusId];
								var keys = Object.keys(vm.mapper.itemClzMapper);
								var isKey = keys.find(m => __status.includes(m));
								newObj.itemClz = isKey ? vm.mapper.itemClzMapper[isKey] : '';
							}
							if (vm.mapper.buttons) {
								newObj.__buttons = JSON.parse(JSON.stringify(vm.mapper.buttons));
								newObj.__buttons.forEach(m => {
									if (m.showWhen) {
										m.show = m.showWhen[1].includes(n[m.showWhen[0]])
									} else {
										m.show != undefined && (m.show = true);
									}
								});
								newObj.__buttons = newObj.__buttons.filter(n => n.show)
							}
							if (vm.mapper.templates) {
								var prop = vm.mapper.templates.prop;
								var templateHtml = '';
								[].concat(n[prop]).forEach(task => {
									templateHtml += vm.getFmtStr(vm.mapper.templates.template, task)
								});
								newObj.__templateHtml = templateHtml;
							}
							if (vm.mapper.footer) {
								var footer = {...JSON.parse(JSON.stringify(vm.mapper.footer))};
                                footer.items.forEach(m => {
                                    if (m.showWhen) {
                                    	m.show = m.showWhen[1].includes(n[m.showWhen[0]])
                                    } else {
										m.show != undefined && (m.show = true);
									}
                                })
                                footer.show = footer.items.some(m => m.show);
								
								newObj.__footer = footer;
							}
							return newObj;
						}));
					} else {
						vm.list = vm.list = vm.list.concat(res2.data);
					}
					
					if (vm.list.length == 0) {
						vm.isEmpty = true;
					}
				});
			},
			getFmtStr (str, n) {
                var vm = this;
				return str.replace(/【([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*】/g, function (d) {
					var prop = d.slice(1, -1);
                    if (prop == 'openId') {
                        return vm.openId;
                    }
					return n[prop];
				}).replace(/《([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*》/g, function (d) {
					var prop = d.slice(1, -1);
					return vm.filterObject.queryObj[prop] || '';
				});
			},
			changeStatusIndex: function (v) {
				var vm = this;
				vm.status.forEach((n, i) => {
					n.active = i == v.index;
				});
				this.statusIndex = v.index;
				this.page = 1;
				this.getList();
			},
			back: function () {
				uni.navigateBack();
			},
			handleExtButtonClick: function (obj, item) {
				var vm = this;
				vm.throttle();
				// debugger
				if (obj.url) {
					vm.gotopage(vm.getFmtStr(obj.url, item), obj.label, item);
				} else if (obj.event) {
					if (obj.event == 'scan') {
						vm.scanQrCode();
					} else if (obj.event == 'phoneCall') {
						uni.makePhoneCall({
							phoneNumber: item[obj.prop]
						})
					}
				} else if (obj.h5) {
					vm.gotoH5Page(vm.getFmtStr(obj.h5, item));
				} else if (obj.api) {
                    var apiUrl = vm.getFmtStr(obj.api, item);

					uni.showModal({
						title: '提示',
						content: obj.apiBeforeTip || '是否确定操作',
						showCancel: true,
						success: function(res2) {
							if(res2.confirm) { 
								uni.showLoading();
								vm.getAndLoad('请求接口', apiUrl, function (res) {
									uni.hideLoading();
									uni.showModal({
										title: '提示',
										content: res.msg || (res.code == 0 ? '操作成功' : '操作失败'),
										showCancel: false,
										success: function(res3) {
											if (res.code == 0) {
												vm.page = 1;
												vm.getList();
											}
										}
									});
								});
							}
							
						}
					});




                } else {
					vm.showDetailCommon(item);
				}
			},
			gotopage(url,title,item){
				if(!url){
					return;
				}
				console.log(url+'?id=' + item.id+'&title='+title)
				uni.navigateTo({
					url: url
				})
			},
			showDetail: function (item) {
				// 通用的信息展示
				uni.navigateTo({
					url: '/pages/shenbao/index?id=' + item.id + '&title=' + item.yqCity
				})
			},
			showDetailCommon: function (item) {
				var vm = this;
				if (vm.pick) {
					// 选择模式
					vm.handleItemPicked(item);
					return;
				}
				if (!vm.detailPage) {
					return;
				}
				if (vm.detailPage.h5) {
					vm.gotoH5Page(vm.getFmtStr(vm.detailPage.h5, item));
				} else {
					var query = encodeURIComponent(JSON.stringify(vm.detailPage));
					uni.navigateTo({
						url: '/pages/shenbao/index?id=' + item.id + '&query=' + query
					})
				}

			},
			handleItemPicked: function (item) {
				var pages = getCurrentPages();
				var prevPage = pages[pages.length - 2]; //上一个页面
				// #ifdef H5
				prevPage.$vm.query = [item] //h5写法
				// #endif
				let check = [item];
				//#ifdef MP-WEIXIN||MP-QQ
				prevPage.setData({
					'callBackData': check,
				}) //小程序写法
				// #endif
				uni.navigateBack();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.u-page {
		.viewBottomBtn {
			display: flex;
			.btn {
				flex: 1;
				margin: 0 10rpx;
			}
		}
		.tab {
			background: #72a572;
			color: #fff;
			margin: 20rpx 30rpx;
			display: inline-block;
			padding: 6rpx 10rpx;
		}
		.buttons {
			height: 70rpx;
			display: flex;
			align-items: center;
			margin: 0 0 0 auto;
			.button {
				margin: 0 30rpx 0 -10rpx;
			}
		}
		.item {
			background: #fff;
			margin: 30rpx;
			border-radius: 30rpx;
			padding: 0 0 15rpx;
			position: relative;
			@mixin itemStyle($argus) {
			  border: 1px solid $argus;
			  color: #fff;
			  background: $argus;
			  .lens .key {
				  color: #fff;
			  }
			}
			&.success {
				@include itemStyle(#7dcca0);
			}
			&.fail {
				@include itemStyle(#E65757);
			}
			&.primary {
				@include itemStyle(#0990F6);
			}
			&.wait {
				@include itemStyle(#F49446);
			}
			&.cancel {
				@include itemStyle(#A7A7A7);
			}
			
			.title {
				font-size: 36rpx;
				padding: 20rpx;
				line-height: 60rpx;
				border-bottom: 1px solid #bedcbe;
				margin: 0 20rpx;
				display: block;
			}
			.lens {
				padding: 0 20rpx;
				margin: 10rpx 0 ;
				display: flex;
				.key {
					margin-right: 20rpx;
					color: #999999;
					min-width: 170rpx;
				}
			}
			.status {
				position: absolute;
				right: 20rpx;
				top: 20rpx;
			}
			.subTags {
				font-size: 26rpx;
				display: inline-block;
				.item {
					background: rgba(8,144,246,0.06);
					color: #0890F6;
					border: 1px solid;
					height: 30rpx;
					display: flex;
					line-height: 30rpx;
					margin: 0;
					border-radius: 10rpx;
					padding: 3rpx 5rpx;
					margin-left: 10rpx;
				}
			}
			.extTags {
				font-size: 26rpx;
				display: flex;
				padding: 10rpx;
				.item {
					background: rgba(8,144,246,0.06);
					color: #081af6;
					border: 1px solid;
					height: 30rpx;
					display: flex;
					line-height: 30rpx;
					margin: 0;
					border-radius: 10rpx;
					padding: 3rpx 5rpx;
					margin-left: 10rpx;
				}
			}
		}
	}

	.mapperlist {
		.statustab {
			background: #fff;
		}
		.item {
			display: flex;
			flex-direction: column;
		}
	}
	.filterObject {
		display: flex;
		justify-content: center;
		/deep/ .u-cell__value {
			@include overfloewEllipsis(2);
			max-width: 470rpx;
		}
	}
</style>
